package org.kim.command;

import org.kim.core.Session;
import org.kim.pojo.Account;
import org.kim.service.AccountService;
import org.kim.utils.Constants;

import java.util.Optional;

public class AccountCommand {

    AccountService accountService=new AccountService();

    public boolean isLogined(){
        Optional<Account> optional=Optional.ofNullable(Session.getAny());
        return optional.isPresent();
    }

    public boolean isAdminRole(){
        return true;
    }

    public String register(String[] commandStrs) throws Exception {
        String accountId= commandStrs[2];
        String role=commandStrs[1];
        String name=commandStrs[2];
        String password=commandStrs[3];
        Account account=new Account(accountId,role,name,password,"ACTIVE");
        boolean result=false;
        if(!accountService.accountExists(accountId)){
            result=accountService.register(account);
        }
        if(result){
           return String.format(Constants.registerSuccess,account.getRole(),account.getName());
        }else{
            return String.format(Constants.registerFail,account.getRole(),account.getName());
        }
    }

    public String login(String[] commandStrs) throws Exception {
        Account inputAccount=new Account();
        inputAccount.setAccountId(commandStrs[1]);
        inputAccount.setPassword(commandStrs[2]);
        Account account=accountService.login(inputAccount);
        if(account!=null){
            return String.format(Constants.loginSuccess,account.getRole(),account.getAccountId());
        }else{
            return String.format(Constants.loginFail,inputAccount.getAccountId());
        }
    }
}
